home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3721 < prev    next >
Encoding:
Text File  |  1996-08-06  |  2.0 KB  |  88 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: Philip Staite <pstaite@vnet.ibm.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Template casting problem
  5. Date: Thu, 25 Jan 1996 13:13:56 -0600
  6. Organization: IBM Rochester, OS/2 Device Driver Team
  7. Message-ID: <3107D674.41C6@vnet.ibm.com>
  8. References: <41@site73.site73.ping.at>
  9. NNTP-Posting-Host: powertool.rchland.ibm.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b4 (X11; I; AIX 1)
  14.  
  15. Michael Geramb wrote:
  16. > Here is a C++ problem that I never managed to solve.
  17. > Imagine you create a template of a class :
  18. > template <class T> class A
  19. > {
  20. >         ...
  21. > };
  22. > This gives a family of classes (instances), say:
  23. > A<short>, A<int>, A<float> etc, which may coexist in one function.
  24. > Then, a problem arises how to cast one instance to another.
  25. > As a more concrete example, one may imagine a template CVector which
  26. > generates short, integer, float and double instances.
  27. > It also generates a very natural (to my mind) wish to cast
  28. > one instance to another.
  29.  
  30. Why, with a templatized function of course! :-)
  31.  
  32. How about something like this:
  33.  
  34.  
  35. #include<iostream.h>
  36.  
  37. // simple vector template
  38. template<class T>
  39. class vec {
  40.   public:
  41.     vec( int x ) : n( x ), a( new T[ n ] ) {}
  42.     ~vec() { delete[] a; }
  43.     T& operator[]( int x ) { return a[ x ]; }
  44.     int len() const { return n; }
  45.   private:
  46.     int n;
  47.     T* a;
  48. };
  49.  
  50.  
  51. // template function that can convert vecs
  52. // relies on cast from B& to A being defined
  53. template<class A, class B>
  54. void castVec( vec<A>& a, vec<B>& b ) {
  55.     for( int i = 0 ; i < a.len() ; ++i )
  56.         a[ i ] = (A) b[ i ]; }
  57.  
  58.  
  59.  
  60. int main() {
  61.     vec<float> fvec( 10 );
  62.     vec<int> ivec( 10 );
  63.     int f;
  64.  
  65.     for( f = 0 ; f < 10 ; ++f )
  66.         fvec[ f ] = f;
  67.  
  68.     castVec( ivec, fvec );
  69.  
  70.     for( f = 0 ; f < 10 ; cout << ivec[ f++ ] << endl );
  71.  
  72.     return 0; }
  73.  
  74.  
  75.  
  76.  
  77.  
  78. -- 
  79.  
  80. Phil Staite, (507) 253-2529, team OS/2
  81. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  82.